<?php

namespace App\Console\Commands;

use App\Models\Book;
use App\Models\Chapter;
use App\Models\Task;
use App\Models\TaskLog;
use App\Services\AudioBookJobService;
use App\Services\AudioBookService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class AudioBook extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:audio-book {task}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     * 下载中 - 0
     * 已下载 - 1
     * 已导入 - 2
     * 翻译-待审校 - 3
     * 翻译-未通过 - 4
     * 翻译-审校通过 - 5
     * 音色-待选取—只有人物关系出来才有 - 6
     * 配音-执行中 - 7
     * 配音-待审校 - 8
     * 配音-未通过 - 9
     * 任务完成 - 10
     *
     */
    public function handle()
    {
        $task = $this->argument('task');
        // 导入内容
        if ($task == 'importBook') {
            $service = new AudioBookService();
            $book = Book::where('status', 1)->where('import_status', 0)->first();
            $result = $service->importBook($book->id);
            if (!empty($result)) {
                $book->import_status = 1;
                $book->status = 2;
                $book->save();
            }
        }

        // 创建任务
        if ($task == 'createTask') {
            $this->createTask();
        }

        if ($task == 'retryJob') {
            $this->retryJob();
        }
    }

    public function createTask()
    {
        $service = new AudioBookJobService();
        $books = Book::where('import_status', 1)->where('task_status', 0)->limit(10)->get();
        foreach ($books as $book) {
            $chapters = Chapter::select('id', 'num')->where('book_id', $book->id)->where('status', 1)->get();
            foreach ($chapters as $chapter) {
                $service->dispatchJob([
                    'book_id' => $book->id,
                    'chapter_id' => $chapter->id,
                    'chapter_num' => $chapter->num,
                    'type' => 'removeInvalidContent',
                    'type_name' => '去废话'
                ]);
            }
            $book->task_status = 1;
            $book->save();
        }
    }

    public function retryJob($job_id = '')
    {
        if (!empty($job_id)) {
            $command = 'php artisan queue:retry ' . $job_id;
        } else {
            $command = 'php artisan queue:retry all';
        }
        exec($command, $output, $returnVar);
        if ($returnVar === 0) {
            return true;
        }

        return false;
    }
}
